/**
 * 简化的Claude服务
 * 整合所有Claude相关功能，减少重复代码
 */
const axios = require("axios");
const { spawn, exec } = require("child_process");
const { promisify } = require("util");
const fs = require("fs");
const path = require("path");
const os = require("os");
const appConfig = require("../config/app-config");
const storageService = require("./storage-service");

const execAsync = promisify(exec);

class SimplifiedClaudeService {
  constructor() {
    this.baseURL = appConfig.api.baseURL;
    this.timeout = appConfig.api.timeout;
    this.builtinPath = null;
    this.isBuiltinAvailable = false;
    this.activeSession = null; // 持久的 Claude 会话
    this.sessionWorkPath = null; // 当前会话的工作路径
    this.init();
  }

  /**
   * 获取存储的配置
   */
  async getStoredConfig() {
    try {
      const result = await storageService.loadModelConfig();
      if (result.success && result.config) {
        return result.config;
      }
      return null;
    } catch (error) {
      console.error("[ClaudeService] 获取存储配置失败:", error);
      return null;
    }
  }

  /**
   * 初始化内置Claude Code
   */
  init() {
    try {
      const possiblePaths = [
        // 开发环境
        path.join(
          process.cwd(),
          "node_modules",
          "@anthropic-ai",
          "claude-code"
        ),
        path.join(__dirname, "../../../node_modules/@anthropic-ai/claude-code"),
        
        // 打包环境（asar: false）- app 目录
        path.join(
          process.resourcesPath || __dirname,
          "app",
          "node_modules",
          "@anthropic-ai",
          "claude-code"
        ),
        
        // 打包环境 - asar.unpacked 目录（兼容旧配置）
        path.join(
          process.resourcesPath || __dirname,
          "app.asar.unpacked",
          "node_modules",
          "@anthropic-ai",
          "claude-code"
        ),
      ];

      console.log("[SimplifiedClaudeService] 尝试查找内置Claude Code...");
      console.log("[SimplifiedClaudeService] process.resourcesPath:", process.resourcesPath);
      console.log("[SimplifiedClaudeService] __dirname:", __dirname);

      for (const testPath of possiblePaths) {
        console.log("[SimplifiedClaudeService] 检测路径:", testPath);
        if (fs.existsSync(testPath)) {
          // 如果路径包含 app.asar，自动替换为 app.asar.unpacked
          let finalPath = testPath;
          if (testPath.includes('app.asar') && !testPath.includes('app.asar.unpacked')) {
            finalPath = testPath.replace('app.asar', 'app.asar.unpacked');
            console.log("[SimplifiedClaudeService] 路径包含 app.asar，替换为:", finalPath);
            
            // 验证替换后的路径是否存在
            if (!fs.existsSync(finalPath)) {
              console.log("[SimplifiedClaudeService] 替换后的路径不存在，使用原路径");
              finalPath = testPath;
            }
          }
          
          this.builtinPath = finalPath;
          this.isBuiltinAvailable = true;
          console.log(
            "[SimplifiedClaudeService] ✅ 找到内置Claude Code:",
            this.builtinPath
          );
          return;
        }
      }

      console.log("[SimplifiedClaudeService] ❌ 未找到内置Claude Code");
    } catch (error) {
      console.error("[SimplifiedClaudeService] 初始化失败:", error);
    }
  }

  /**
   * 检查Claude Code是否可用
   */
  async checkClaudeCode() {
    // 优先检查内置版本
    if (this.isBuiltinAvailable) {
      return {
        installed: true,
        source: "builtin",
        path: this.builtinPath,
      };
    }

    // 检查系统安装
    try {
      await execAsync("claude --version");
      return {
        installed: true,
        source: "system",
      };
    } catch (error) {
      return {
        installed: false,
        source: "none",
      };
    }
  }

  /**
   * 获取Claude Code信息
   */
  async getClaudeCodeInfo() {
    const checkResult = await this.checkClaudeCode();

    if (checkResult.installed) {
      return {
        success: true,
        info: {
          installed: true,
          source: checkResult.source,
          path: checkResult.path,
          shouldShowInstallPage: false,
        },
      };
    }

    return {
      success: true,
      info: {
        installed: false,
        shouldShowInstallPage: true,
      },
    };
  }

  /**
   * 获取版本信息
   */
  async getClaudeCodeVersion() {
    console.log("[ClaudeService] getClaudeCodeVersion 调用");
    console.log("[ClaudeService] isBuiltinAvailable:", this.isBuiltinAvailable);
    console.log("[ClaudeService] builtinPath:", this.builtinPath);
    
    if (this.isBuiltinAvailable) {
      try {
        console.log("[ClaudeService] 使用内置版本检测");
        // 直接执行命令行获取版本，不需要环境变量
        const result = await this.executeBuiltinVersionCommand();
        console.log("[ClaudeService] 内置版本检测成功:", result);
        return {
          success: true,
          version: {
            success: true,
            version: result.output.trim(),
          },
        };
      } catch (error) {
        console.error("[ClaudeService] 内置版本获取失败:", error.message);
        // 内置版本获取失败，尝试系统版本
      }
    } else {
      console.log("[ClaudeService] 内置不可用，尝试系统版本");
    }

    // 尝试系统安装的 claude
    try {
      const { stdout } = await execAsync("claude --version");
      console.log("[ClaudeService] 系统版本检测成功:", stdout);
      return {
        success: true,
        version: {
          success: true,
          version: stdout.trim(),
        },
      };
    } catch (error) {
      console.error("[ClaudeService] 系统版本获取失败:", error.message);
      return {
        success: false,
        version: {
          success: false,
          error: "未找到 Claude Code，请检查安装",
        },
      };
    }
  }

  /**
   * 执行内置版本命令（不需要环境变量）
   */
  async executeBuiltinVersionCommand() {
    return new Promise((resolve, reject) => {
      // 尝试多个可能的 node 路径
      const possibleNodePaths = [
        process.env.NODE,
        "/Users/lixingchen/.nvm/versions/node/v22.16.0/bin/node",
        "/usr/local/bin/node",
        "/usr/bin/node",
        "node", // 使用系统 PATH
      ].filter(Boolean);

      const nodePath = possibleNodePaths[0];
      const claudeScript = path.join(this.builtinPath, "cli.js");

      console.log("[ClaudeService] 获取版本:", {
        nodePath,
        claudeScript,
        exists: fs.existsSync(claudeScript),
      });

      // 检查 cli.js 是否存在
      if (!fs.existsSync(claudeScript)) {
        reject(new Error("cli.js 文件不存在"));
        return;
      }

      // 简单执行 node cli.js --version
      const command = `"${nodePath}" "${claudeScript}" --version`;
      console.log("[ClaudeService] 执行命令:", command);

      const child = spawn(command, {
        stdio: ["pipe", "pipe", "pipe"],
        shell: true,
      });

      let stdout = "";
      let stderr = "";

      const timeout = setTimeout(() => {
        child.kill("SIGTERM");
        reject(new Error("获取版本超时"));
      }, 5000); // 5秒超时

      child.stdout.on("data", (data) => {
        stdout += data.toString();
        console.log("[ClaudeService] version stdout:", data.toString());
      });

      child.stderr.on("data", (data) => {
        stderr += data.toString();
        console.log("[ClaudeService] version stderr:", data.toString());
      });

      child.on("close", (code) => {
        clearTimeout(timeout);
        console.log("[ClaudeService] 版本检测结束:", { code, stdout, stderr });
        if (code === 0 || stdout) {
          // 即使退出码不是0，只要有stdout就认为成功
          resolve({
            success: true,
            output: stdout || stderr,
            source: "builtin",
          });
        } else {
          reject(new Error(stderr || `获取版本失败，退出码: ${code}`));
        }
      });

      child.on("error", (error) => {
        clearTimeout(timeout);
        console.error("[ClaudeService] 版本检测错误:", error);
        reject(error);
      });
    });
  }

  /**
   * 执行内置命令
   */
  async executeBuiltinCommand(args, options = {}) {
    if (!this.isBuiltinAvailable) {
      throw new Error("内置Claude Code不可用");
    }

    // 确保 options.env 存在
    const env = options.env || {};

    try {
      // 直接使用 JavaScript API 而不是命令行
      console.log("[ClaudeService] 使用 JavaScript API 执行");

      // 动态导入 Claude Code 模块
      const claudeCodePath = path.join(this.builtinPath, "sdk.mjs");
      const { query } = await import(claudeCodePath);

      // 执行任务
      const task = args[args.length - 1]; // 最后一个参数是任务描述
      console.log("[ClaudeService] 执行任务:", task);

      // 设置环境变量
      if (env.ANTHROPIC_AUTH_TOKEN) {
        process.env.ANTHROPIC_AUTH_TOKEN = env.ANTHROPIC_AUTH_TOKEN;
      }
      if (env.ANTHROPIC_BASE_URL) {
        process.env.ANTHROPIC_BASE_URL = env.ANTHROPIC_BASE_URL;
      }

      // 使用 query 函数执行任务
      const response = query({
        prompt: task,
        options: {
          cwd: options.cwd || process.cwd(),
          env: { ...process.env, ...env },
        },
      });

      let result = "";
      for await (const message of response) {
        if (message.type === "assistant") {
          result += message.message.content[0].text || "";
        } else if (message.type === "result" && message.subtype === "success") {
          result = message.result;
          break;
        }
      }

      return {
        success: true,
        output: result,
        source: "builtin",
      };
    } catch (error) {
      console.error("[ClaudeService] JavaScript API 执行失败:", error);

      // 回退到命令行执行
      console.log("[ClaudeService] 回退到命令行执行");
      return this.executeBuiltinCommandFallback(args, options);
    }
  }

  /**
   * 回退到命令行执行
   */
  async executeBuiltinCommandFallback(args, options = {}) {
    return new Promise((resolve, reject) => {
      // 使用系统的 Node.js 而不是 Electron 的 Node.js
      const nodePath =
        process.env.NODE ||
        "/Users/lixingchen/.nvm/versions/node/v22.16.0/bin/node";
      const claudeScript = path.join(this.builtinPath, "cli.js");

      // 确保 options.env 存在
      const env = options.env || {};
      const authToken = env.ANTHROPIC_AUTH_TOKEN || "";
      const baseURL = env.ANTHROPIC_BASE_URL || "";

      console.log("[ClaudeService] 执行命令:", {
        nodePath,
        claudeScript,
        args,
        cwd: options.cwd || process.cwd(),
        hasAuthToken: !!authToken,
        hasBaseURL: !!baseURL,
      });

      // 使用 shell 执行，确保环境变量正确传递
      let command;
      if (authToken && baseURL) {
        command = `ANTHROPIC_AUTH_TOKEN="${authToken}" ANTHROPIC_BASE_URL="${baseURL}" "${nodePath}" "${claudeScript}" ${args.join(
          " "
        )}`;
      } else {
        // 如果没有环境变量（如 --version 命令），直接执行
        command = `"${nodePath}" "${claudeScript}" ${args.join(" ")}`;
      }
      console.log("[ClaudeService] 执行 shell 命令:", command);

      const child = spawn(command, {
        stdio: ["pipe", "pipe", "pipe"],
        cwd: options.cwd || process.cwd(),
        env: { ...process.env, ...env },
        shell: true,
      });

      let stdout = "";
      let stderr = "";

      // 设置超时
      const timeout = setTimeout(() => {
        console.log("[ClaudeService] 进程超时，强制终止");
        child.kill("SIGTERM");
        reject(new Error("命令执行超时"));
      }, 25000); // 25秒超时

      child.stdout.on("data", (data) => {
        stdout += data.toString();
        console.log("[ClaudeService] stdout:", data.toString());
      });

      child.stderr.on("data", (data) => {
        stderr += data.toString();
        console.log("[ClaudeService] stderr:", data.toString());
      });

      child.on("close", (code) => {
        clearTimeout(timeout);
        console.log("[ClaudeService] 进程结束:", { code, stdout, stderr });
        if (code === 0) {
          resolve({
            success: true,
            output: stdout,
            source: "builtin",
          });
        } else {
          reject(new Error(stderr || `命令执行失败，退出码: ${code}`));
        }
      });

      child.on("error", (error) => {
        clearTimeout(timeout);
        console.error("[ClaudeService] 进程错误:", error);
        reject(error);
      });

      // 如果有输入数据，写入到子进程
      if (options.input) {
        child.stdin.write(options.input);
        child.stdin.end();
      }
    });
  }

  /**
   * 执行任务
   */
  async executeTask(apiKey, task, model = "claude-3-sonnet-20240229") {
    try {
      // 获取存储的配置
      const config = await this.getStoredConfig();
      const authToken = config?.apiKey || apiKey;
      const baseURL = config?.baseURL || this.baseURL;
      const selectedModel = config?.model || model;

      // 优先使用内置版本
      if (this.isBuiltinAvailable) {
        const result = await this.executeBuiltinCommand([task], {
          env: {
            ANTHROPIC_AUTH_TOKEN: authToken,
            ANTHROPIC_BASE_URL: baseURL,
          },
        });
        return {
          success: true,
          result: result.output,
          source: "builtin",
        };
      }

      // 回退到API调用
      const response = await axios.post(
        `${baseURL}/chat/completions`,
        {
          model: selectedModel,
          messages: [{ role: "user", content: task }],
          max_tokens: 4000,
        },
        {
          headers: {
            Authorization: `Bearer ${authToken}`,
            "Content-Type": "application/json",
          },
          timeout: this.timeout,
        }
      );

      return {
        success: true,
        result: response.data.choices[0].message.content,
        source: "api",
      };
    } catch (error) {
      return {
        success: false,
        message: error.response?.data?.error?.message || error.message,
        source: this.isBuiltinAvailable ? "builtin" : "api",
      };
    }
  }

  /**
   * 验证API Key
   */
  async validateApiKey(apiKey) {
    try {
      if (this.isBuiltinAvailable) {
        // 使用内置版本验证
        await this.executeBuiltinCommand(["auth", "--api-key", apiKey]);
        return {
          success: true,
          valid: true,
          source: "builtin",
        };
      }

      // 使用API验证
      const response = await axios.get(`${this.baseURL}/models`, {
        headers: { Authorization: `Bearer ${apiKey}` },
        timeout: this.timeout,
      });

      return {
        success: true,
        valid: response.status === 200,
        source: "api",
      };
    } catch (error) {
      return {
        success: false,
        valid: false,
        message: error.response?.data?.error?.message || error.message,
        source: this.isBuiltinAvailable ? "builtin" : "api",
      };
    }
  }

  /**
   * 安装Claude Code
   */
  async installClaudeCode() {
    if (this.isBuiltinAvailable) {
      const versionResult = await this.getClaudeCodeVersion();
      return {
        success: true,
        message: `内置Claude Code已就绪 (${
          versionResult.version?.version || "未知版本"
        })`,
        source: "builtin",
      };
    }

    return {
      success: false,
      message: "内置Claude Code不可用，请检查应用安装",
      source: "builtin",
    };
  }

  /**
   * 无头模式执行
   */
  async executeClaudeHeadless(apiKey, task) {
    try {
      // 获取存储的配置
      const config = await this.getStoredConfig();
      const authToken = config?.apiKey || apiKey;
      const baseURL =
        config?.baseURL || "https://open.bigmodel.cn/api/anthropic";

      console.log("[ClaudeService] 使用配置:", {
        authToken: authToken ? "***" + authToken.slice(-4) : "none",
        baseURL,
      });

      if (this.isBuiltinAvailable) {
        const result = await this.executeBuiltinCommand(["--print", task], {
          env: {
            ANTHROPIC_AUTH_TOKEN: authToken,
            ANTHROPIC_BASE_URL: baseURL,
          },
        });
        return {
          success: true,
          output: result.output,
          source: "builtin",
          exitCode: 0,
        };
      }

      // 回退到系统命令
      const { stdout, stderr } = await execAsync(`claude --print "${task}"`, {
        env: {
          ...process.env,
          ANTHROPIC_AUTH_TOKEN: authToken,
          ANTHROPIC_BASE_URL: baseURL,
        },
        timeout: 60000,
      });

      return {
        success: true,
        output: stdout || stderr,
        source: "system",
        exitCode: 0,
      };
    } catch (error) {
      // 最终回退到API调用
      const config = await this.getStoredConfig();
      const authToken = config?.apiKey || apiKey;
      const apiResult = await this.executeTask(authToken, task);
      return {
        success: apiResult.success,
        output: apiResult.success ? apiResult.result : apiResult.message,
        source: "api",
        exitCode: apiResult.success ? 0 : 1,
      };
    }
  }

  /**
   * 无头模式执行（用于测试，强制使用传入的 API Key）
   */
  async executeClaudeHeadlessForTest(apiKey, task) {
    console.log("[ClaudeService] ========== executeClaudeHeadlessForTest 开始 ==========");
    console.log("[ClaudeService] task:", task);
    console.log("[ClaudeService] apiKey:", apiKey ? "***" + apiKey.slice(-4) : "none");
    
    try {
      // 获取存储的配置，但只使用 baseURL，强制使用传入的 apiKey
      const config = await this.getStoredConfig();
      const authToken = apiKey; // 强制使用传入的 apiKey
      const baseURL =
        config?.baseURL || "https://open.bigmodel.cn/api/anthropic";

      console.log("[ClaudeService] 测试模式 - 使用配置:", {
        authToken: authToken ? "***" + authToken.slice(-4) : "none",
        baseURL,
        forceUseProvidedKey: true,
        isBuiltinAvailable: this.isBuiltinAvailable,
        builtinPath: this.builtinPath
      });

      if (this.isBuiltinAvailable) {
        console.log("[ClaudeService] 🔹 尝试使用内置 Claude Code...");
        try {
          const result = await this.executeBuiltinCommand(["--print", task], {
            env: {
              ANTHROPIC_AUTH_TOKEN: authToken,
              ANTHROPIC_BASE_URL: baseURL,
            },
          });
          console.log("[ClaudeService] ✅ 内置命令执行成功:", result);
          return {
            success: true,
            output: result.output,
            source: "builtin",
            exitCode: 0,
          };
        } catch (builtinError) {
          console.error("[ClaudeService] ❌ 内置命令执行失败:", builtinError.message);
          console.error("[ClaudeService] 错误堆栈:", builtinError.stack);
          console.log("[ClaudeService] 🔹 尝试回退到系统命令...");
          // 继续执行系统命令回退
        }
      } else {
        console.log("[ClaudeService] 🔹 内置不可用，尝试系统命令");
      }

      // 回退到系统命令
      try {
        console.log("[ClaudeService] 执行系统 claude 命令...");
        const { stdout, stderr } = await execAsync(`claude --print "${task}"`, {
          env: {
            ...process.env,
            ANTHROPIC_AUTH_TOKEN: authToken,
            ANTHROPIC_BASE_URL: baseURL,
          },
          timeout: 60000,
        });

        console.log("[ClaudeService] ✅ 系统命令执行成功");
        return {
          success: true,
          output: stdout || stderr,
          source: "system",
          exitCode: 0,
        };
      } catch (systemError) {
        console.error("[ClaudeService] ❌ 系统命令执行失败:", systemError.message);
        console.error("[ClaudeService] 错误堆栈:", systemError.stack);
        console.log("[ClaudeService] 🔹 尝试回退到 API 调用...");
      }

      // 最终回退到API调用，使用传入的 apiKey
      console.log("[ClaudeService] 使用 API 直接调用");
      const apiResult = await this.executeTask(apiKey, task);
      console.log("[ClaudeService] API 调用结果:", apiResult);
      
      return {
        success: apiResult.success,
        output: apiResult.success ? apiResult.result : apiResult.message,
        source: "api",
        exitCode: apiResult.success ? 0 : 1,
      };
    } catch (error) {
      console.error("[ClaudeService] ========== executeClaudeHeadlessForTest 最终失败 ==========");
      console.error("[ClaudeService] 错误:", error.message);
      console.error("[ClaudeService] 错误堆栈:", error.stack);
      return {
        success: false,
        output: error.message,
        source: "error",
        exitCode: 1
      };
    }
  }

  /**
   * 启动持久的 Claude 会话
   */
  async startClaudeSession(apiKey, workPath) {
    // 如果已有会话且工作路径相同，直接返回
    if (this.activeSession && this.sessionWorkPath === workPath) {
      console.log("[ClaudeService] 使用现有会话");
      return {
        success: true,
        type: this.activeSession.type,
        workPath: workPath,
        reused: true, // 标记为重用的会话
      };
    }

    // 关闭旧会话
    if (this.activeSession) {
      console.log("[ClaudeService] 关闭旧会话");
      await this.stopClaudeSession();
    }

    // 获取配置
    const config = await this.getStoredConfig();
    const authToken = config?.apiKey || apiKey;
    const baseURL = config?.baseURL || "https://api.deepseek.com/anthropic";

    console.log("[ClaudeService] 启动 Claude 会话:", {
      workPath,
      hasAuthToken: !!authToken,
    });

    try {
      // 使用内置 Claude Code 的 JavaScript API
      if (this.isBuiltinAvailable) {
        const claudeCodePath = path.join(this.builtinPath, "sdk.mjs");
        const claudeModule = await import(claudeCodePath);

        this.activeSession = {
          type: "builtin",
          module: claudeModule,
          workPath: workPath,
          authToken: authToken,
          baseURL: baseURL,
        };

        this.sessionWorkPath = workPath;

        console.log("[ClaudeService] Claude 会话启动成功（内置）");
        return {
          success: true,
          type: "builtin",
          workPath: workPath,
        };
      }

      // 如果内置不可用，标记使用命令行模式
      this.activeSession = {
        type: "command",
        workPath: workPath,
        authToken: authToken,
        baseURL: baseURL,
      };

      this.sessionWorkPath = workPath;

      console.log("[ClaudeService] Claude 会话启动成功（命令行）");
      return {
        success: true,
        type: "command",
        workPath: workPath,
      };
    } catch (error) {
      console.error("[ClaudeService] 启动会话失败:", error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 停止 Claude 会话
   */
  async stopClaudeSession() {
    if (this.activeSession) {
      console.log("[ClaudeService] 停止 Claude 会话");
      this.activeSession = null;
      this.sessionWorkPath = null;
    }
  }

  /**
   * 使用当前会话执行任务（支持流式输出）
   * @param {string} task - 任务描述
   * @param {Function} onStream - 流式回调函数，接收每个消息片段
   */
  async executeWithSession(task, onStream = null) {
    if (!this.activeSession) {
      throw new Error("没有活跃的 Claude 会话，请先连接");
    }

    console.log("[ClaudeService] 使用会话执行任务（流式）:", {
      type: this.activeSession.type,
      workPath: this.activeSession.workPath,
      taskLength: task?.length,
      hasStreamCallback: !!onStream
    });

    if (this.activeSession.type === "builtin") {
      // 使用内置 JavaScript API
      try {
        const { query } = this.activeSession.module;

        // 设置环境变量
        process.env.ANTHROPIC_AUTH_TOKEN = this.activeSession.authToken;
        process.env.ANTHROPIC_BASE_URL = this.activeSession.baseURL;

        console.log("[ClaudeService] 调用 Claude query API（流式模式）");

        // 构建带中文指示的提示词
        const promptWithLanguage = `请使用中文回答和交流。任务：${task}`;

        const response = query({
          prompt: promptWithLanguage,
          options: {
            cwd: this.activeSession.workPath,
            permissionMode: "bypassPermissions", // 🔥 关键：绕过权限检查，自动批准所有操作
            env: {
              ...process.env,
              ANTHROPIC_AUTH_TOKEN: this.activeSession.authToken,
              ANTHROPIC_BASE_URL: this.activeSession.baseURL,
            },
          },
        });

        let result = "";
        let hasResult = false;
        let messageCount = 0;

        for await (const message of response) {
          messageCount++;
          console.log("[ClaudeService] 收到消息 #" + messageCount + ":", message.type);

          // 🔥 流式发送消息到前端
          if (onStream) {
            onStream({
              type: message.type,
              messageIndex: messageCount,
              timestamp: Date.now()
            });
          }

          if (message.type === "assistant" && message.message?.content) {
            const content = message.message.content[0];
            if (content?.text) {
              const textChunk = content.text;
              result += textChunk;
              hasResult = true;
              
              // 🔥 实时发送文本片段
              if (onStream) {
                onStream({
                  type: 'text-chunk',
                  text: textChunk,
                  fullText: result,
                  messageIndex: messageCount,
                  timestamp: Date.now()
                });
              }
            }
          } else if (message.type === "result" && message.subtype === "success") {
            result = message.result || result;
            hasResult = true;
            
            // 🔥 发送最终结果
            if (onStream) {
              onStream({
                type: 'final-result',
                result: result,
                messageIndex: messageCount,
                timestamp: Date.now()
              });
            }
            break;
          } else if (message.type === "error") {
            // 🔥 发送错误消息
            if (onStream) {
              onStream({
                type: 'error',
                error: message.error || "执行出错",
                messageIndex: messageCount,
                timestamp: Date.now()
              });
            }
            throw new Error(message.error || "执行出错");
          }
        }

        if (!hasResult) {
          throw new Error("未获取到有效结果");
        }

        return {
          success: true,
          output: result,
          source: "builtin-session",
          workPath: this.activeSession.workPath,
          messageCount: messageCount
        };
      } catch (error) {
        console.error("[ClaudeService] JavaScript API 执行失败:", error);
        throw error;
      }
    } else {
      // 使用命令行模式（暂不支持流式）
      return this.executeWithCommand(task);
    }
  }

  /**
   * 使用命令行执行（回退方案）
   */
  async executeWithCommand(task) {
    const escapedTask = task.replace(/"/g, '\\"');
    console.log(
      "🚀 ~ SimplifiedClaudeService ~ executeWithCommand ~ escapedTask:",
      escapedTask
    );
    const command = `cd "${this.activeSession.workPath}" && claude "${escapedTask}"`;

    console.log("[ClaudeService] 执行命令:", command);

    return new Promise((resolve) => {
      const child = spawn(command, {
        env: {
          ...process.env,
          ANTHROPIC_AUTH_TOKEN: this.activeSession.authToken,
          ANTHROPIC_BASE_URL: this.activeSession.baseURL,
          CLAUDE_AUTO_APPROVE: "true",
          CLAUDE_WORKING_DIR: this.activeSession.workPath,
        },
        stdio: ["pipe", "pipe", "pipe"],
        shell: true,
        cwd: this.activeSession.workPath,
      });

      let stdout = "";
      let stderr = "";

      const timeout = setTimeout(() => {
        console.log("[ClaudeService] 命令执行超时，强制结束");
        child.kill("SIGTERM");

        if (stdout || stderr) {
          resolve({
            success: true,
            output: stdout || stderr,
            source: "command-session",
            workPath: this.activeSession.workPath,
            timedOut: true,
          });
        } else {
          resolve({
            success: false,
            error: "命令执行超时且无输出",
            source: "command-session",
          });
        }
      }, 60000);

      child.stdout.on("data", (data) => {
        const output = data.toString();
        stdout += output;
        console.log("[ClaudeService] stdout:", output);
      });

      child.stderr.on("data", (data) => {
        const output = data.toString();
        stderr += output;
        console.log("[ClaudeService] stderr:", output);
      });

      child.on("close", (code) => {
        clearTimeout(timeout);
        console.log("[ClaudeService] 命令结束:", {
          code,
          stdoutLength: stdout.length,
        });

        if (code === 0 || stdout) {
          resolve({
            success: true,
            output: stdout || stderr,
            source: "command-session",
            exitCode: code,
            workPath: this.activeSession.workPath,
          });
        } else {
          resolve({
            success: false,
            error: stderr || `命令执行失败，退出码: ${code}`,
            source: "command-session",
            exitCode: code,
          });
        }
      });

      child.on("error", (error) => {
        clearTimeout(timeout);
        console.error("[ClaudeService] 命令错误:", error);
        resolve({
          success: false,
          error: error.message,
          source: "command-session",
        });
      });
    });
  }

  /**
   * 系统Claude Code执行（保持向后兼容）
   */
  async executeSystemClaude(apiKey, task, workPath = null) {
    // 获取存储的配置
    const config = await this.getStoredConfig();
    const authToken = config?.apiKey || apiKey;
    const baseURL = config?.baseURL || "https://open.bigmodel.cn/api/anthropic";

    // 确定工作目录
    const cwd = workPath || process.cwd();

    console.log("[ClaudeService] 执行系统 Claude:", {
      hasAuthToken: !!authToken,
      baseURL,
      workPath: cwd,
      taskLength: task?.length,
    });

    return new Promise((resolve, reject) => {
      // 使用 cd 命令切换到工作目录，然后执行 claude
      const escapedTask = task.replace(/"/g, '\\"');
      console.log(
        "🚀 ~ SimplifiedClaudeService ~ executeSystemClaude ~ escapedTask:",
        escapedTask
      );
      const command = workPath
        ? `cd "${workPath}" && claude "${escapedTask}"`
        : `claude "${escapedTask}"`;

      console.log("[ClaudeService] 执行命令:", command);

      const child = spawn(command, {
        env: {
          ...process.env,
          ANTHROPIC_AUTH_TOKEN: authToken,
          ANTHROPIC_BASE_URL: baseURL,
          CLAUDE_AUTO_APPROVE: "true", // 启用自动批准
          CLAUDE_WORKING_DIR: cwd,
        },
        stdio: ["pipe", "pipe", "pipe"],
        shell: true,
        cwd: cwd, // 设置工作目录
      });

      let stdout = "";
      let stderr = "";

      const timeout = setTimeout(() => {
        console.log("[ClaudeService] 命令执行超时，但有输出，强制结束");
        child.kill("SIGTERM");

        // 即使超时，如果有输出也认为成功
        if (stdout || stderr) {
          resolve({
            success: true,
            output: stdout || stderr,
            source: "system",
            exitCode: -1,
            workPath: cwd,
            timedOut: true,
            message: "任务执行超时，但已获取部分输出",
          });
        } else {
          resolve({
            success: false,
            error: "系统命令执行超时（60秒）且无输出",
            source: "system",
            timedOut: true,
          });
        }
      }, 60000); // 60秒超时

      child.stdout.on("data", (data) => {
        const output = data.toString();
        stdout += output;
        console.log("[ClaudeService] stdout:", output);
      });

      child.stderr.on("data", (data) => {
        const output = data.toString();
        stderr += output;
        console.log("[ClaudeService] stderr:", output);
      });

      child.on("close", (code) => {
        clearTimeout(timeout);
        console.log("[ClaudeService] 命令执行结束:", {
          code,
          stdoutLength: stdout.length,
          stderrLength: stderr.length,
        });

        if (code === 0 || stdout) {
          // 如果有输出，即使退出码不是0也认为成功
          resolve({
            success: true,
            output: stdout || stderr,
            source: "system",
            exitCode: code,
            workPath: cwd,
          });
        } else {
          resolve({
            success: false,
            error: stderr || `系统命令执行失败，退出码: ${code}`,
            source: "system",
            exitCode: code,
            workPath: cwd,
          });
        }
      });

      child.on("error", (error) => {
        clearTimeout(timeout);
        console.error("[ClaudeService] 命令执行错误:", error);
        resolve({
          success: false,
          error: error.message,
          source: "system",
        });
      });
    });
  }

  /**
   * 测试检测器
   */
  async testDetector() {
    const checkResult = await this.checkClaudeCode();
    return {
      installed: checkResult.installed,
      source: checkResult.source,
      builtinAvailable: this.isBuiltinAvailable,
      builtinPath: this.builtinPath,
    };
  }
}

module.exports = new SimplifiedClaudeService();
